package cn.orangelite.ai.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.orangelite.ai.domain.*;
import cn.orangelite.ai.domain.dto.ChatBodyDTO;
import cn.orangelite.ai.mapper.AiGptKeyMapper;
import cn.orangelite.ai.service.*;
import cn.orangelite.common.core.utils.DateUtils;
import cn.orangelite.common.core.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//4204+7565+9440+7120.44+(2366.85+5375.49)
/**
 * gptkey
 Service业务层处理
 *
 * @author dongfaqing
 * @date 2024-01-16
 */
@Service
public class AiGptKeyServiceImpl extends ServiceImpl<AiGptKeyMapper,AiGptKey> implements IAiGptKeyService
{
//    @Value("${gpt.defaultModel}")
//    private String defaultModel;
    @Value("${langchain.domain}")
    private String langchainDomain;

    @Autowired
    private AiGptKeyMapper aiGptKeyMapper;

    @Autowired
    private IAiReplyConfigService aiReplyConfigService;

    @Autowired
    private IAiGptMessageLogService aiGptMessageLogService;

    @Autowired
    private IAiInitConfigDataService aiInitConfigDataService;

    @Autowired
    private IAiWechatUserService aiWechatUserService;

    @Autowired
    private IAiWechatLogService aiWechatLogService;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 查询gptkey

     *
     * @param id gptkey
    主键
     * @return gptkey

     */
    @Override
    public AiGptKey selectAiGptKeyById(Long id)
    {
        return aiGptKeyMapper.selectAiGptKeyById(id);
    }

    /**
     * 查询gptkey
     列表
     *
     * @param aiGptKey gptkey

     * @return gptkey

     */
    @Override
    public List<AiGptKey> selectAiGptKeyList(AiGptKey aiGptKey)
    {
        return aiGptKeyMapper.selectAiGptKeyList(aiGptKey);
    }

    /**
     * 新增gptkey

     *
     * @param aiGptKey gptkey

     * @return 结果
     */
    @Override
    public int insertAiGptKey(AiGptKey aiGptKey)
    {
        aiGptKey.setCreateTime(DateUtils.getNowDate());
        return aiGptKeyMapper.insertAiGptKey(aiGptKey);
    }

    /**
     * 修改gptkey

     *
     * @param aiGptKey gptkey

     * @return 结果
     */
    @Override
    public int updateAiGptKey(AiGptKey aiGptKey)
    {
        return aiGptKeyMapper.updateAiGptKey(aiGptKey);
    }

    /**
     * 批量删除gptkey

     *
     * @param ids 需要删除的gptkey
    主键
     * @return 结果
     */
    @Override
    public int deleteAiGptKeyByIds(Long[] ids)
    {
        return aiGptKeyMapper.deleteAiGptKeyByIds(ids);
    }

    /**
     * 删除gptkey
     信息
     *
     * @param id gptkey
    主键
     * @return 结果
     */
    @Override
    public int deleteAiGptKeyById(Long id)
    {
        return aiGptKeyMapper.deleteAiGptKeyById(id);
    }

    /**
     * 本地部署的，暂时不需要
     *
     * @param chatBodyDTO
     * @return
     */
//    @Override
//    public String wechatGpt(ChatBodyDTO chatBodyDTO) {
//        chatBodyDTO.setStream(false);
//        chatBodyDTO.setModel(defaultModel);
//
////        AiGptMessageLog aiGptMessageLog = aiGptMessageLogService.saveMessageLog(chatDTO.getLogId(), chatDTO.getMessage());
////
////        List<Messages> messageList = JSONUtil.toList(aiGptMessageLog.getUseValue(), Messages.class);
////        chatBodyDTO.setMessages(messageList);
//
//        AiGptKey aiGptKey = new AiGptKey();
//        aiGptKey.setState(0L);
//        aiGptKey.setType(4);
//        List<AiGptKey> aiGptKeys = aiGptKeyMapper.selectAiGptKeyList(aiGptKey);
//        Collections.shuffle(aiGptKeys);
//
//
//        //gpt请求
//        HttpResponse request = HttpRequest.post("https://api.openai.com/v1/chat/completions")
//                .contentType("application/json")
//                .header("Authorization", "Bearer "+aiGptKeys.get(0).getKey())
//                .body(JSONUtil.toJsonStr(chatBodyDTO))
//                .execute();
//
//
//        return request.body();
////        return request.bodyStream();
//    }


    @Override
    public ArrayList<HashMap<String, Object>> wechatGpt(ChatBodyDTO chatBodyDTO) {
        //获取发送者的信息
        AiWechatUser wechatUser = aiWechatUserService.getOne(Wrappers.<AiWechatUser>lambdaQuery().eq(AiWechatUser::getUsername, chatBodyDTO.getUsername()));
        //获取初始化配置信息
        AiInitConfigData aiInitConfigData = aiInitConfigDataService.list().get(0);

        ArrayList<HashMap<String,Object>> resultData = new ArrayList<>();

        //如果是管理员发送
        if(wechatUser.getUsername().equals(aiInitConfigData.getUsername())){
            if(chatBodyDTO.getQuery().startsWith("cmd@")){
                HashMap<String, Object> result = new HashMap<>();
                result.put("type","ai");
                Integer close = 1;
                if(chatBodyDTO.getQuery().startsWith("cmd@恢复")){
                    close = 0;
                    result.put("answer","已恢复");
                }
                if(chatBodyDTO.getQuery().startsWith("cmd@关闭")){
                    close = 1;
                    result.put("answer","已关闭");
                }

                String username = chatBodyDTO.getQuery().substring(6);
                AiWechatUser targetUser = aiWechatUserService.getOne(Wrappers.<AiWechatUser>lambdaQuery().eq(AiWechatUser::getUsername, username.trim()));
                targetUser.setClose(close);
                aiWechatUserService.updateById(targetUser);
                resultData.add(result);
                return resultData;
            }

        }

        //如果发送者已关闭，则不自动回复
        if(wechatUser.getClose()==1){
            HashMap<String, Object> result = new HashMap<>();
            result.put("type","none");
            result.put("answer","无需回复");
            resultData.add(result);
            return resultData;
        }

        //除了文字的所有类型
        if(!chatBodyDTO.getType().equals("Text")){
            HashMap<String, Object> result = new HashMap<>();
            result.put("type","artificial");
            result.put("answer","发送除了文件外的其他消息");
            resultData.add(result);
            wechatUser.setClose(1);
            aiWechatUserService.updateById(wechatUser);
            return resultData;
        }

        //如果配置了指定回复，可后台设置发送文字或图片或文件
        List<AiReplyConfig> aiReplyConfigList = aiReplyConfigService.list();
        for (AiReplyConfig replyConfig : aiReplyConfigList){
            String[] questionArray = replyConfig.getQuestion().split("\\|");
            if(Arrays.asList(questionArray).contains(chatBodyDTO.getQuery())){
                if(StringUtils.isNotEmpty(replyConfig.getReply())){
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("type","text");
                    result.put("answer",replyConfig.getReply());
                    resultData.add(result);
                }
                if(StringUtils.isNotEmpty(replyConfig.getFile())){
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("type","file");
                    result.put("answer",replyConfig.getReply().split(","));
                    resultData.add(result);
                }
                return resultData;
            }
        }

        AiWechatLog human = new AiWechatLog();
        human.setType("human");
        human.setContent(chatBodyDTO.getQuery());
        human.setUsername(chatBodyDTO.getUsername());
        human.setCreateTime(DateUtils.getNowDate());
        aiWechatLogService.save(human);

        //请求ai做出回复
        AiGptKey aiGptKey = new AiGptKey();
        aiGptKey.setState(0L);
        aiGptKey.setType(1);
        List<AiGptKey> aiGptKeys = aiGptKeyMapper.selectAiGptKeyList(aiGptKey);

        AiGptKey aiGptKey2 = new AiGptKey();
        aiGptKey2.setState(0L);
        aiGptKey2.setType(2);
        List<AiGptKey> aiGptKeys2 = aiGptKeyMapper.selectAiGptKeyList(aiGptKey2);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("openai_api_key",aiGptKeys.get(0).getKey());
        paramMap.put("model",aiGptKeys.get(0).getModel());
        paramMap.put("embeddings",aiGptKeys2.get(0).getModel());
        paramMap.put("template",aiInitConfigData.getTemplate());
        paramMap.put("query",chatBodyDTO.getQuery());
        String aiResult = HttpUtil.post(langchainDomain+"/gpt/knowledge_chat/"+chatBodyDTO.getUsername(), JSONUtil.toJsonStr(paramMap));

        JSONObject response = JSONUtil.parseObj(aiResult);
        String answer = "";
        if(response.getJSONObject("message").getStr("answer")!=null){
            answer = response.getJSONObject("message").getStr("answer");
        }else if(response.getJSONObject("message").getStr("content")!=null){
            answer = response.getJSONObject("message").getStr("content");
        }


        HashMap<String, Object> result = new HashMap<>();
        //判断模板是否设置了指定回复，如果匹配，就向管理员的微信发送消息，通知人工回复
        for(String v : aiInitConfigData.getFixedMessage().split("\\|")){
            if((v + "。").equals(answer) || (v + ".").equals(answer) || v.equals(answer)){
                result.put("type","artificial");
                result.put("answer","需要人工处理");
                resultData.add(result);
                //处理微信用户，下次发消息就不该自动回答了
                wechatUser.setClose(1);
                aiWechatUserService.updateById(wechatUser);
                return resultData;
            }
        }

        AiWechatLog ai = new AiWechatLog();
        ai.setType("ai");
        ai.setContent(answer);
        ai.setUsername(chatBodyDTO.getUsername());
        ai.setCreateTime(DateUtils.getNowDate());
        aiWechatLogService.save(ai);


        //以上都通过，则用ai的回答回复
        result.put("type","ai");
        result.put("answer",answer);
        resultData.add(result);
        return resultData;
    }

}
